<!-- 定标结果确认 -->
<template>
  <view>
    <u-form
      :model="model"
      :rules="rules"
      ref="form"
      labelPosition="top"
      labelWidth="auto"
      :labelStyle="{
      	fontSize: '14px',
      	color: '#B2B2B2',
      	lineHight: '20px'
      }"
    >
      <view class="basic-style">
        <view class="basic-title basic-border">基本信息</view>
        <u-form-item label="单据编号" prop="documentNo" required>
          <u--input v-model="model.documentNo" disabled></u--input>
        </u-form-item>
        <u-form-item label="申请人" prop="handlerId" required>
          <h-select-person-input
            style="width: 100%"
            disabled
            v-model="model.handlerId"
            placeholder="请选择申请人"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            objectField="model.handlerId"
          ></h-select-person-input>
        </u-form-item>
        <u-form-item label="申请时间" prop="createTime" required>
          <u--input v-model="model.createTime" disabled></u--input>
        </u-form-item>
        <u-form-item label="申请部门" prop="applyDept" required>
          <h-select-depart-input
            disabled
            v-model="model.applyDept"
            :departName="model.proposerDeptText"
            placeholder="请选择部门"
            border="surround"
            style="width: 100%"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            :title.sync="model.proposerDeptText"
          ></h-select-depart-input>
        </u-form-item>
        <u-form-item label="管理员" prop="carAdmin" required>
          <h-select-person-input-popup
            disabled
            v-model="model.carAdmin"
            style="width: 100%"
            placeholder="请选择管理员"
            searchPlaceholder="请输入"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
          ></h-select-person-input-popup>
        </u-form-item>
        <u-form-item label="费用所属团队" prop="businessUnit" required>
          <h-select-team-input
						:disabled="disableSubmit"
            style="width: 100%"
            v-model="model.businessUnit"
            objectField="model.businessUnit"
            placeholder="请选择费用所属团队"
            border="surround"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }"
            :tdlx="3"
          />
        </u-form-item>
        <u-form-item label="申请车辆" prop="carId">
          <text style="flex-shrink: 0; margin-right: 1em; color: #1890ff;" @click="showCarInfo = true">{{ model.carId_dictText }}</text>
          <u-button @click="showCarInfo = true" size="small">查看汽车详情</u-button>
        </u-form-item>
        <u-form-item label="关联项目" prop="projectId">
          <h-select-project-input-popup
						:disabled="disableSubmit"
            :proDisabled="true"
            :projectStatus="'2'"
            ref="projectSelect"
            v-model="model.projectId"
            style="width: 100%"
            placeholder="请选择关联项目"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
          ></h-select-project-input-popup>
        </u-form-item>
        <u-form-item label="是否需要驾驶员" prop="isDriver" required>
          <h-select-input-tag
            class="w-100"
						:disabled="disableSubmit"
            v-model="model.isDriver"
            objectField="model.isDriver"
            placeholder="请选择是否需要驾驶员"
            border="surround"
            dictName="YES_OR_NO"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }"
          ></h-select-input-tag>
        </u-form-item>
        <u-form-item label="预计归还日期" prop="usingEndTime" required>
          <h-time-select
            mode="date"
						:disabled="disableSubmit"
            v-model="model.usingEndTime"
            placeholder="请选择预计归还日期"
            border="surround"
            suffixIcon="calendar-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
          ></h-time-select>
        </u-form-item>
        <u-form-item label="用车类型" prop="usingType" required>
          <h-select-input-tag
            class="w-100"
						:disabled="disableSubmit"
            v-model="model.usingType"
            objectField="model.usingType"
            placeholder="请选择用车类型"
            border="surround"
            dictName="using_type"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }"
          ></h-select-input-tag>
        </u-form-item>
				
        <u-form-item label="预定日期" prop="reserveStartTime" required>
					<!-- <h-Calendar-select
						style="width: 100%" 
						:disabled="disableSubmit"
						border="surround" 
						v-model="reserveDate"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{color: '#B2B2B2'}" 
						@confirm="onCalendarConfirm"
					  placeholder="请选择预定日期">
					</h-Calendar-select> -->
          <!-- <h-time-select
            mode="datetime"
            v-model="model.reserveStartTime"
            placeholder="请选择预定日期始"
            border="surround"
          ></h-time-select> -->
					<h-calendar-datetime-select
						style="width: 100%"
						:disabled="disableSubmit"
						v-model="reserveDate"
						@confirm="onCalendarConfirm"
						placeholder="请选择预定日期"
					></h-calendar-datetime-select>
        </u-form-item>
        <!-- <u-form-item label="预定日期" prop="reserveEndTime" required>
          <h-time-select
            mode="datetime"
            v-model="model.reserveEndTime"
            placeholder="请选择预定日期止"
            border="surround"
          ></h-time-select>
        </u-form-item> -->
        <!-- <u-form-item label="驾驶员" prop="driver">
          <h-select-person-input-popup
            v-model="model.driver"
            style="width: 100%"
            placeholder="请选择驾驶员"
            searchPlaceholder="请输入"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
          ></h-select-person-input-popup>
        </u-form-item>
        <u-form-item label="是否已还车" prop="isReturnCar">
          <h-select-input-tag
            class="w-100"
            v-model="model.isReturnCar"
            objectField="model.isReturnCar"
            placeholder="请选择是否已还车"
            border="surround"
            dictName="yes_no"
          ></h-select-input-tag>
        </u-form-item>
        <u-form-item label="还车日期" prop="returnCarTime">
          <h-time-select
            mode="datetime"
            v-model="model.returnCarTime"
            placeholder="请选择还车日期"
            border="surround"
            suffixIcon="calendar-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
          ></h-time-select>
        </u-form-item>
        <u-form-item label="使用公里数" prop="kilometers">
          <u--input type="number" v-number-normal placeholder="请输入使用公里数" v-model="model.kilometers"></u--input>
        </u-form-item> -->
        <u-form-item label="事由" prop="subjectMatter" required >
          <u--textarea confirm-type="send" v-model="model.subjectMatter" placeholder="请输入事由" :disabled="disableSubmit"></u--textarea>
        </u-form-item>
        <u-form-item label="备注" prop="remark" >
          <u--textarea confirm-type="send" v-model="model.remark" placeholder="备注" :disabled="disableSubmit"></u--textarea>
        </u-form-item>
      </view>

      <view class="basic-style">
        <view class="basic-title basic-border">附件信息</view>
        <view class="py-1 space-y-1" style="width: 100%">
          <view style="color: red">提示：请等待附件上传完成，再点击保存，否则附件无法保存成功！</view>
          <h-upload-file v-model="model.fileInfo" :isIcon="false" v-if="!disableSubmit"></h-upload-file>
          <file-list v-if="model.fileInfo" v-model="model.fileInfo" :isDelete="!disableSubmit"></file-list>
        </view>
      </view>

      <PopupCarInfo :show.sync="showCarInfo" :carInfo="carInfo" />

      <view class="space-x-1 px-1 btn_position" v-if="!disableSubmit">
				<u-button type="primary" :disabled="isSubmit" :plain="true" text="保存" :loading="loading" @click="onDraft"></u-button>
        <u-button type="primary" :disabled="isSubmit" text="保存并提交" :loading="loading" @click="onSubmit"></u-button>
      </view>
			<view class="space-x-1 px-1 btn_position" v-else>
			  <u-button type="primary" text="关闭" @click="onClose"></u-button>
			</view>
			<view style="height: 100rpx;"></view>
    </u-form>
		<u-toast ref="uToast"></u-toast>
		<ProcessNodeConfiguration ref="processConfig" @ok="onOk"></ProcessNodeConfiguration>
  </view>
</template>

<script>
import { mapState } from 'vuex'
import moment from 'moment'
import http from '@/utils/request/index'
import specialHttp from '@/utils/request/specialIndex' // 特殊请求方式，直接返回res
import { add,edit, generatedFormNumber, queryByCarId,queryById } from '@/api/hr/CarUserInfoForm'
import PopupCarInfo from './components/PopupCarInfo.vue'
import ProcessNodeConfiguration from '@/components/ProcessNodeConfiguration/ProcessNodeConfiguration.vue' // 流程节点配置人员选择弹窗
import fileList from '@/pages/synergy/components/fileList.vue'
export default {
  name: 'CarUserInfoForm',
  components: {
    PopupCarInfo,
    fileList,
		ProcessNodeConfiguration
  },
  data() {
    return {
			isSubmit: false,
      showBusinessSegment: false,
      exportTeamId: '',
      flag: false,
      index: null,
      loading: false,
      id: '',
      exportWarehouseList: [],
      foldWarehouseList: [],
      dataSource2: [],
      basicForm: {},
      // formData: [
      //   {
      //     id: 411283512599,
      //     materialBillId: 'WL01343',
      //     brand: '农夫山泉',
      //     specification: '6L',
      //     amount: '6',
      //     provisionSmall: '1535177002383859714',
      //     materialName: '1627503793494896641',
      //     referencePrice: null,
      //     unit: '4',
      //     budgetAmount: '12',
      //   },
      // ],
      formData: [],
      model: {
        checkStatus: 0,
        documentNo: '',
        handlerId: '',
        createTime: '',
        applyDept: '',
        carAdmin: '',
        businessUnit: '',
        carId: '',
        projectId: '',
        isDriver: '',
        usingEndTime: '',
        usingType: '',
        reserveStartTime: '',
        reserveEndTime: '',
        driver: '',
        isReturnCar: '',
        returnCarTime: '',
        kilometers: '',
        subjectMatter: '',
        remark: '',
        fileInfo: null,
      },
      rules: {
				documentNo: [{ required: true, message: '请输入单据编号!', trigger: ['blur', 'change'] }],
				handlerId: [{ required: true, message: '请选择申请人!', trigger: ['blur', 'change'] }],
				applyDept: [{ required: true, message: '请选择申请部门!', trigger: 'change' }],
				createTime: [{ required: true, message: '请选择申请时间!', trigger: ['blur', 'change'] }],
        usingType: [{ required: true, message: '请选择用车类型!', trigger: 'blur' }],
        carId: [{ required: true, message: '请选择申请车辆!', trigger: 'blur' }],
        reserveStartTime: [{ required: true, message: '请选择预定日期!', trigger: 'change' }],
        businessUnit: [{ required: true, message: '请选择费用所属团队!', trigger: 'change' }],
        isDriver: [{ required: true, message: '请选择是否需要驾驶员!', trigger: 'blur' }],
        usingStartTime: [{ required: true, message: '请选择用车日期!', trigger: 'change' }],
        usingEndTime: [{ required: true, message: '请选择预计归还日期!', trigger: 'change' }],
        subjectMatter: [{ required: true, message: '请输入事由!', trigger: 'blur' }],
      },
			reserveDate: [], // 预定日期
      info: null,
      showCarInfo: false,
      carInfo: null,
			//代码生成后需手动设置流程编码
			flowCode: 'onl_erp_car_using',
			formUrl: '/oa/erpcarusing/modules/ErpCarUsingForm',
			formUrlMobile: '/pages/synergy/erpCarUsingList',
			processId: '1551852856610439169',
			beanName: 'carUseFlow'
    }
  },
  onLoad(options) {
    if (options.info) {
      this.info = JSON.parse(options.info)
    }
		if (options.id) {
		  this.id = options.id
		}
		
		if (options.disableSubmit) {
		  this.disableSubmit = options.disableSubmit == 'true'? true : false
		} else {
			this.disableSubmit = false
		}
  },
  created() {
    if (this.info) {
      this.initForm()
    } else {
      this.initInfo()
    }
  },
  computed: {
    ...mapState(['userInfo']),
  },
  methods: {
    // 生成单号，反写到编号和标题
    generatedFormNumber() {
      generatedFormNumber({ prefix: 'YC', subSystemCode: '04' }).then((res) => {
        if (res.success) {
          // 单据编号
          this.$set(this.model, 'documentNo', res.result)
          // 标题 申请人-单据编号
          this.$set(this.model, 'bpmBizTitle', this.userInfo?.employee?.name + '-' + res.result)
        }
      })
    },
    // 初始化新增需要的数据
    initForm() {
      const record = this.info
      this.model.handlerId = this.userInfo.empId //当前登录人
      this.model.applyDept = this.userInfo.deptId //当前登录人部门
      this.$set(this.model, 'carAdmin', record.carAdmin) // 管理员名称
      this.$set(this.model, 'carAdmin_dictText', record.carAdmin_dictText) // 管理员名称
      this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss')
      if (record.startStr) {
        this.$set(this.model, 'reserveStartTime', record.startStr)
        this.$set(this.model, 'reserveEndTime', record.endStr)
        this.reserveStartDate = record.startStr
        this.reserveEndDate = record.endStr
      }
      if (record.id) {
        this.$set(this.model, 'carId', record.id)
      }
      queryByCarId({ id: this.model.carId }).then((res) => {
        if (res.success) {
          this.carInfo = res.result
        }
      })
      if (record.carName) {
        this.$set(this.model, 'carId_dictText', record.carName)
      }
      this.$set(this.model, 'createTime', moment().format('YYYY-MM-DD HH:mm'))
      this.formDisabled = false
      this.add_edit = 'add'
      this.generatedFormNumber()
    },
		// 选择预定日期
		onCalendarConfirm(val) {
			if (val && val.length) {
				// this.$set(this.model, 'reserveStartTime', val[0]+' 00:00:00')
				// this.$set(this.model, 'reserveEndTime', val[val.length - 1]+' 23:59:59')
				// this.reserveDate = val[0] + '至' + val[val.length - 1]
				
				if (val && val.length && val.length == 2) {
					this.$set(this.model, 'reserveStartTime', val[0]+' 00:00:00')
					this.$set(this.model, 'reserveEndTime', val[val.length - 1]+' 23:59:59')
					this.reserveDate = [val[0], val[val.length - 1]]
				}
			}
		},
    async initInfo() {
      const response = await queryById({ id: this.id })
      const data = response?.result || {}
			this.model = Object.assign({}, data)
			queryByCarId({ id: this.model.carId }).then((res) => {
			  if (res.success) {
			    this.carInfo = res.result
			  }
			})
			// this.reserveDate = this.model.reserveStartTime.split(' ')[0] + '至' + this.model.reserveEndTime.split(' ')[0]
			this.reserveDate = [this.model.reserveStartTime.split(' ')[0], this.model.reserveEndTime.split(' ')[0]]
      // for (const key in data) {
      //   if (Object.hasOwnProperty.call(this.model, key)) {
      //     this.model[key] = data[key]
      //   }
      // }
    },
    validateForm() {
      return this.$refs.form.validate()
    },
		async isBeginProcess() {
			let param ={
				carId: this.model.carId,
				reserveStartTime: this.model.reserveStartTime,
				reserveEndTime: this.model.reserveEndTime
			}
			return	http.get('/api/erp/erpcarusing/erpCarUsing/checkUsingCar', param).then( res => {
				if (res.result.length > 0) {
						// this.$refs.uToast.show({
						//   message: '该车辆本时段已预约，请选择其他车辆或者其他时段预约',
						//   type: 'default'
						// })
						this.$refs.uToast.show({
							message: '该车辆本时段已预约，请选择其他车辆或者其他时段预约',
							type: 'default',
							complete () {
								if (getCurrentPages().length > 1) {
									uni.navigateBack()
								} else {
									uni.reLaunch({
										url: '/pages/home/home'
									})
								}
								
							}
						})
						// this.isSubmit = false
						return Promise.reject(res.message)
				} else {
						return Promise.resolve()
				}
			})
		},
    async onSubmit() {
      await this.validateForm()
      this.isSubmit = true
      try {
        this.loading = true
				var url = ''
				if (this.id) {
					url = edit
				} else {
					url = add
				}
        const response = await url({
          ...this.model,
        })
        // this.$u.toast(response.message)
        if (response.success) {
          var that = this
          await this.isBeginProcess()
          // 获取流程列表
          if (this.model.id) {
          	this.getProcessList(this.model.id)
          } else {
          // 判断添加的时候是否有返回id值
          	if (response.result) {
          		this.getProcessList(response.result)
          	}
          
          }
          this.$refs.uToast.show({
          	message: response.message,
          	type: 'default',
          	complete () {
          		// that.isSubmit = false
          	}
          })
        }
      } finally {
        this.loading = false
      }
    },
		// 获取流程列表
		getProcessList (id) {
			if (this.isSubmit) {
				this.$refs.processConfig.showPopup = true
				this.$refs.processConfig.formUrl = this.formUrl
				this.$refs.processConfig.formUrlMobile = this.formUrlMobile
				this.$refs.processConfig.flowCode = this.flowCode
				this.$refs.processConfig.edit(id, this.processId, this.beanName)
			}
		},
		// 提交流程成功
		onOk () {
			this.$refs.uToast.show({
				message: '提交成功',
				type: 'success',
				complete () {
					if (getCurrentPages().length > 1) {
						uni.navigateBack()
					} else {
						uni.reLaunch({
							url: '/pages/home/home'
						})
					}
					
				}
			})
		},
    async onDraft() {
      await this.validateForm()
			this.isSubmit = true
			try {
			  this.loading = true
				var url = ''
				if (this.id) {
					url = edit
				} else {
					url = add
				}
			  const response = await url({
			    ...this.model
			  })
			  if (response.success) {
					this.$refs.uToast.show({
						message: response.message,
						type: 'default',
						complete () {
							this.isSubmit = false
							if (getCurrentPages().length > 1) {
								uni.navigateBack()
							} else {
								uni.reLaunch({
									url: '/pages/home/home'
								})
							}
							
						}
					})
			  }
			} finally {
			  this.loading = false
			}
    },
		
		onClose () {
			if (getCurrentPages().length > 1) {
				uni.navigateBack()
			} else {
				uni.reLaunch({
					url: '/pages/home/home'
				})
			}
		},
  },
  watch: {
    tenderFormData: {
      immediate: true,
      handler(val) {
        if (val?.length) {
          const total = val.reduce((total, item) => {
            return total + item.amount * item.budgetAmount
          }, 0)
          this.$set(this.model, 'projectBudget', String(total))
        } else {
          this.$set(this.model, 'projectBudget', String(0))
        }
      },
    },
  },
}
</script>

<style scoped lang="scss">
@import url('@/assets/inputStyle.scss');
.trip-form-data {
  ::v-deep {
    .u-form-item__body {
      padding-top: 2px;
      padding-bottom: 2px;
    }
  }
}
.checkbox-item {
  display: flex;
  align-items: center;
}
</style>
